package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.descriptor.FormDTO;
import org.aplikator.client.shared.descriptor.PropertyDTO;
import org.aplikator.client.shared.rpc.marshaller.WidgetMarshallingUtils.WidgetType;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

import java.util.List;

@ClientMarshaller(FormDTO.class)
@ServerMarshaller(FormDTO.class)
@SuppressWarnings("unchecked")
public class FormDTOMarshaller extends AbstractNullableMarshaller<FormDTO> {

	/*@Override
	public Class<FormDTO> getTypeHandled() {
		return FormDTO.class;
	}*/

	@Override
	public FormDTO[] getEmptyArray() {
		return new FormDTO[0];
	}

	@Override
	public FormDTO doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			FormDTO fdto = new FormDTO();
			EJObject object = o.isObject();
			DemarshallingUtils.clientDescriptorBaseUnMarshall(object, fdto);
			
			boolean flag = DemarshallingUtils. safeBool(object,"horizontal");
			fdto.setHorizontal(flag);

			if (DemarshallingUtils.containsAndNotNull(object,"layout")) {
				WidgetType wt = WidgetMarshallingUtils.WidgetType.lookup(object.get("layout"));
				fdto.setLayout(wt.demarshall(object.get("layout"), ctx));
			}
			if (DemarshallingUtils.containsAndNotNull(object,"properties")) {
				List props = DemarshallingUtils.listUnMarshall(object.get("properties"), ctx, PropertyDTO.class.getName());
				fdto.setProperties(props);
			}
			
			return fdto;
		} else return null;
	}

	@Override
	public String doNotNullMarshall(FormDTO o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.clientDescriptorBase(builder, o).append(',');
		MarshallingUtils.bool("horizontal", o.isHorizontal(), builder).append(',');
		MarshallingUtils.key("properties",builder).append(':');
		MarshallingUtils.listMarshall(builder, o.getProperties(), ctx, PropertyDTO.class.getName()).append(',');
		MarshallingUtils.key("layout",builder).append(':');
		WidgetType wt = WidgetMarshallingUtils.WidgetType.lookup(o.getLayout());
		wt.marshall(builder, o.getLayout(), ctx);		
		builder.append('}');
		return builder.toString();
	}
}
